//
//  VVHomePictureView.swift
//  Weibo
//
//  Created by 王惠平 on 2017/3/31.
//  Copyright © 2017年 Will Wang. All rights reserved.
//

import UIKit
import SDWebImage
import SnapKit


//每项的间距
private let itemMargin: CGFloat = 5

//每项的宽度
private let itemWidth: CGFloat = (ScreenWidth - itemMargin * 2 - HomeCellMargin * 2) / 3

class VVHomePictureView: UICollectionView {

   //懒加载控件
    fileprivate lazy var messageLabel: UILabel = UILabel(fonSize: 20, textColor: UIColor.blue, text: "")
    
    //图片数据源
    var picUrls: [VVHomePictureInfo]? {
        
        didSet {
            
            //messageLabel.text = "\(picUrls?.count ?? 0)"
            
            //根据图片的个数计算配图的大小
            calcSize(count: picUrls?.count ?? 0)
            
            //外界设置图片数据源的源的时候需要重新加载数据
            reloadData()
        
        }
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowLayout = UICollectionViewFlowLayout()
        
        //设置每项item的大小
        flowLayout.itemSize = CGSize(width:itemWidth , height: itemWidth)
        
        //设置item的间距
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setupUI() 
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加控件设置约束
    private func setupUI() {
        
        //注册cell
        register(VVHomePictureViewCell.self, forCellWithReuseIdentifier:HomePictureViewCellIdentifer )
        
        //设置数据源代理对象
        dataSource = self
        
        addSubview(messageLabel)
        
        backgroundColor = UIColor(white: 0.95, alpha: 1.0)
        
        messageLabel.snp.makeConstraints { (make) in
            
            make.center.equalTo(self)
        }
    
    }
    
    fileprivate func calcSize(count: Int) {
        
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        //判断是否单张图片
        if count == 1 {
            
            //表示从本地获取下载的单张图片的大小作为配图大小
            //获取图片的地址
            let imageUrl = picUrls?.first?.thumbnail_pic
            
            //从本地获取下载的图片,key表示下载的图片地址
            if let localImage = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: imageUrl) {
                
                //表示本地一定会有图片
                //处理单张图片过窄问题
                var localImageSize = localImage.size
                
                if localImageSize.width < 80 {
                    
                    //指定宽度
                    let currentWidth: CGFloat = 80
                    
                    //计算后的高度
                    var currentHeight: CGFloat = currentWidth / localImageSize.width * localImageSize.height
                    
                    if  currentHeight > 150 {
                        
                        currentHeight = 150
                    }
                    
                    //计算的大小
                    localImageSize = CGSize(width: currentWidth, height: currentHeight)
                }
                //更新约束
                self.snp.updateConstraints({ (make) in
                    
                    make.size.equalTo(localImageSize)
                })
                
                //相依的每项cell的大小改成图片的大小,单张图片的配图要和cell的大小保持同步
                flowLayout.itemSize = localImageSize

                
            } else {
                
                //本地没有找到,使用默认计算的图片的大小
                //更新约束
                self.snp.updateConstraints({ (make) in
                    
                    make.size.equalTo(CGSize(width: itemWidth, height: itemWidth))
                })
                
                //没有找到图片,使用之前计算好的cell的大小
                flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
                
            }
       
            return

        }
        
        //计算列数
        let cols = count > 3 ? 3 : count
        
        //计算行数
        let rows = (count - 1) / 3 + 1
        
        //计算当前配图的宽度
        let currenWidth = CGFloat(cols) * itemWidth + CGFloat(cols - 1) * itemMargin
        
        //计算当前配图的高度
        let currenHeight = CGFloat(rows) * itemWidth + CGFloat(rows - 1) * itemMargin
        
        //更新约束
        self.snp.updateConstraints { (make) in
            
            make.size.equalTo(CGSize(width: currenWidth, height: currenHeight))
        }
        
        //多张图片,每个图片的大小根据之前计算的每个cell的大小是一样的
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
    }

}

extension VVHomePictureView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomePictureViewCellIdentifer, for: indexPath) as! VVHomePictureViewCell
    
        //获取模型数据
        let pictureInfo = picUrls![indexPath.row]
        
        cell.pictureInfo = pictureInfo
        
        return cell
    }
}

//使用自定义cell展示图片
class VVHomePictureViewCell: UICollectionViewCell {
    
    //懒加载控件
    fileprivate lazy var imageView: UIImageView = {
        
        let imageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        
        //使用原始比例显示图片
        imageView.contentMode = .scaleAspectFill
        
        //裁剪超出的视图
        imageView.clipsToBounds = true
        
        return imageView
    }()
    
    fileprivate lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
    //绑定数据
    var pictureInfo: VVHomePictureInfo? {
        
        didSet {
            
            //加载图片
            if let imageUrl = pictureInfo?.thumbnail_pic {
                
                imageView.sd_setImage(with: URL(string: imageUrl), placeholderImage: UIImage(named: "timeline_image_placeholder"))
                
                if  imageUrl.hasSuffix(".gif") {
                    
                    //gif图片
                    gifImageView.isHidden = false
                    
                } else {
                    
                    //不是gif图片
                    gifImageView.isHidden = true
                }
            }
            
        }

    }
    
    override init(frame: CGRect) {
       
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
    contentView.addSubview(imageView)
        contentView.addSubview(gifImageView)
        
        imageView.snp.makeConstraints { (make) in
            
            make.edges.equalTo(contentView)
        }
        
        gifImageView.snp.makeConstraints { (make) in
            
            make.trailing.bottom.equalTo(imageView)
        }
    }
    
}
